<?php

namespace app\admin\controller;


use app\LoginNotController;
use app\model\MyException;
use app\model\tablenot\tool\LonLatAddress;
use app\model\tablenot\tool\RedisService;
use app\model\tablenot\tool\Tool;
use app\model\tool\IpLimit;
use think\captcha\facade\Captcha;
use hg\apidoc\annotation as Apidoc;

/**
 * @Apidoc\Title("不需要登录接口")
 */
class CommonController extends LoginNotController
{
    public function indexAction()
    {
        echo "forbid";die;
    }


    public function testAction(): void
    {
        try {
            $userObj = invoke('User')->findOne(['id'=>1]);
            //throw new MyException("验证码不正确");
            //$userObj = User::instance()->findOne(['id'=>1]);
            dump($userObj);
        //RedisService::instance()->set('test', 'test1111');
        //$a = Cache::store('redis')->hgetall('test');
        } catch (MyException $e) {
            echo $e->toJson();
        }
    }

    /**
     * @Apidoc\Title("验证码")
     * @Apidoc\Method("GET")
     * @Apidoc\Param("SecrUser", type="string",require=true, desc="验证码值-建议使用浏览器唯一识别码")
     */
    public function verifyAction()
    {
        Tool::checkParam(['SecrUser'], $this->get);
        $secruser = $this->get['SecrUser'];
        ob_clean();
        return Captcha::create(null, false, $secruser);
    }

    /**
     * @Apidoc\Title("超管登录")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("name", type="string",require=true, desc="用户名")
     * @Apidoc\Param("password", type="string",require=true, desc="密码")
     * @Apidoc\Param("captcha", type="string",require=true, desc="验证码")
     * @Apidoc\Param("SecrUser", type="string",require=true, desc="验证码值-建议使用浏览器唯一识别码")
     * @Apidoc\Param("lon", type="string",require=false, desc="精度")
     * @Apidoc\Param("lat", type="string",require=false, desc="纬度")
     */
    public function loginAction()
    {
        try {
            Tool::checkParam(['name', 'password', 'captcha', 'SecrUser'], $this->post);
            $name = $this->post['name'];
            $password = $this->post['password'];
            $captcha = $this->post['captcha'];
            $SecrUser = $this->post['SecrUser'];
            $yzmKey = 'yzm_' . $SecrUser;
            if ($captcha != RedisService::instance()->get($yzmKey)) {
                throw new MyException("验证码不正确");
            }
            // 验证码通过后删除验证码
            RedisService::instance()->del($yzmKey);

            if(IpLimit::instance()->isLoginLimit()){
                throw new MyException('密码错误次数过多，请联系代理商');
            }

            // 超管只有一个admin账户，不能修改和删除这个账户
            $userWhere = array();
            if ($name == "admin") {
                $userWhere[] = ['name', '=', $name];
                $userWhere[] = ['role', '=', Role::instance()->getAdminId()];
            } else {
                $userWhere[] = ['parent_id', '=', 1];
                $userWhere[] = ['name', '=', $name];
                $userWhere[] = ['role', '=', Role::instance()->getSonId()];
            }
            $UserObj = User::instance()->findOne($userWhere, true);
            // 检查当前是否限制登录
            if (empty($UserObj)) {
                throw new MyException('账号或密码不正确');
            }
            if ($UserObj['password'] != Tool::password($password)) {
                IpLimit::instance()->setLoginLimit();
                throw new MyException('账号或密码不正确');
            }
            if ($UserObj['status'] != 1) {
                throw new MyException('当前账号禁止登录');
            }

            // 获取用户经纬度
            $LonLatModel = new LonLatAddress($this->post['lon'], $this->post['lat']);
            $address = $LonLatModel->get();

            //更新用户的最近登录时间
            $UserObj['last_login_time'] = $this->time;
            $UserObj['login_address'] = $address;
            User::instance()->updateOne($UserObj);

            // 挤账号功能
            //User::instance()->loginOnlyOne($UserObj['id']);

            $loginId = $UserObj['id'];
            $dataUserId = $UserObj['id'];

            // 如果是子账户
            if ($UserObj['role'] == Role::instance()->getSonId()) {
                $dataUserId = $UserObj['parent_id'];
            }
            $token = User::instance()->token_encode($loginId, $dataUserId);
            $UserObj = User::instance()->toBaseColumn($UserObj);
            $UserObj['token'] = $token;
            if($UserObj['sub_role_id']!=0){
                $subRoleInfo = SubRole::instance()->findOne(['id'=>$UserObj['sub_role_id']]);
                $roleName = $subRoleInfo['name'];
            }else{
                $roleName = '超管';
            }
            $UserObj['role_name'] = $roleName;
            //记录登录日志
            UserLoginLog::instance()->addLoginLog($UserObj,"超管",$address);
            $this->setData($UserObj);
            $this->sendJson();
        } catch (MyException $e) {
            echo $e->toJson();
        }
    }
}
